package cn.ibizlab.businesscentral.core.sales.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Map;
import java.util.HashSet;
import java.util.HashMap;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.math.BigInteger;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.ObjectUtils;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Lazy;
import cn.ibizlab.businesscentral.core.sales.domain.Goal;
import cn.ibizlab.businesscentral.core.sales.filter.GoalSearchContext;
import cn.ibizlab.businesscentral.core.sales.service.IGoalService;

import cn.ibizlab.businesscentral.util.helper.CachedBeanCopier;
import cn.ibizlab.businesscentral.util.helper.DEFieldCacheMap;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ibizlab.businesscentral.core.sales.mapper.GoalMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

/**
 * 实体[目标] 服务对象接口实现
 */
@Slf4j
@Service("GoalServiceImpl")
public class GoalServiceImpl extends ServiceImpl<GoalMapper, Goal> implements IGoalService {


    protected cn.ibizlab.businesscentral.core.sales.service.IGoalService goalService = this;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.IGoalRollupQueryService goalrollupqueryService;
    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.base.service.IMetricService metricService;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.logic.IGoalActiveLogic activeLogic;

    @Autowired
    @Lazy
    protected cn.ibizlab.businesscentral.core.sales.service.logic.IGoalCloseLogic closeLogic;

    protected int batchSize = 500;

    @Override
    @Transactional
    public boolean create(Goal et) {
        fillParentData(et);
        if(!this.retBool(this.baseMapper.insert(et)))
            return false;
        CachedBeanCopier.copy(get(et.getGoalid()),et);
        return true;
    }

    @Override
    public void createBatch(List<Goal> list) {
        list.forEach(item->fillParentData(item));
        this.saveBatch(list,batchSize);
    }

    @Override
    @Transactional
    public boolean update(Goal et) {
        fillParentData(et);
        if(!update(et,(Wrapper) et.getUpdateWrapper(true).eq("goalid",et.getGoalid())))
            return false;
        CachedBeanCopier.copy(get(et.getGoalid()),et);
        return true;
    }

    @Override
    public void updateBatch(List<Goal> list) {
        list.forEach(item->fillParentData(item));
        updateBatchById(list,batchSize);
    }

    @Override
    @Transactional
    public boolean remove(String key) {
        boolean result=removeById(key);
        return result ;
    }

    @Override
    public void removeBatch(Collection<String> idList) {
        removeByIds(idList);
    }

    @Override
    @Transactional
    public Goal get(String key) {
        Goal et = getById(key);
        if(et==null){
            et=new Goal();
            et.setGoalid(key);
        }
        else{
        }
        return et;
    }

    @Override
    public Goal getDraft(Goal et) {
        fillParentData(et);
        return et;
    }

    @Override
    @Transactional
    public Goal active(Goal et) {
        activeLogic.execute(et);
         return et ;
    }

    @Override
    public boolean checkKey(Goal et) {
        return (!ObjectUtils.isEmpty(et.getGoalid()))&&(!Objects.isNull(this.getById(et.getGoalid())));
    }
    @Override
    @Transactional
    public Goal close(Goal et) {
        closeLogic.execute(et);
         return et ;
    }

    @Override
    @Transactional
    public boolean save(Goal et) {
        if(!saveOrUpdate(et))
            return false;
        return true;
    }

    @Override
    @Transactional
    public boolean saveOrUpdate(Goal et) {
        if (null == et) {
            return false;
        } else {
            return checkKey(et) ? this.update(et) : this.create(et);
        }
    }

    @Override
    public boolean saveBatch(Collection<Goal> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
        return true;
    }

    @Override
    public void saveBatch(List<Goal> list) {
        list.forEach(item->fillParentData(item));
        saveOrUpdateBatch(list,batchSize);
    }


	@Override
    public List<Goal> selectByRollupqueryactualdecimalid(String goalrollupqueryid) {
        return baseMapper.selectByRollupqueryactualdecimalid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupqueryactualdecimalid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupqueryactualdecimalid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupqueryactualintegerid(String goalrollupqueryid) {
        return baseMapper.selectByRollupqueryactualintegerid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupqueryactualintegerid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupqueryactualintegerid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupqueryactualmoneyid(String goalrollupqueryid) {
        return baseMapper.selectByRollupqueryactualmoneyid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupqueryactualmoneyid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupqueryactualmoneyid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupquerycustomdecimalid(String goalrollupqueryid) {
        return baseMapper.selectByRollupquerycustomdecimalid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupquerycustomdecimalid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupquerycustomdecimalid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupquerycustomintegerid(String goalrollupqueryid) {
        return baseMapper.selectByRollupquerycustomintegerid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupquerycustomintegerid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupquerycustomintegerid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupquerycustommoneyid(String goalrollupqueryid) {
        return baseMapper.selectByRollupquerycustommoneyid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupquerycustommoneyid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupquerycustommoneyid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupqueryinprogressdecimalid(String goalrollupqueryid) {
        return baseMapper.selectByRollupqueryinprogressdecimalid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupqueryinprogressdecimalid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupqueryinprogressdecimalid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupqueryinprogressintegerid(String goalrollupqueryid) {
        return baseMapper.selectByRollupqueryinprogressintegerid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupqueryinprogressintegerid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupqueryinprogressintegerid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByRollupqueryinprogressmoneyid(String goalrollupqueryid) {
        return baseMapper.selectByRollupqueryinprogressmoneyid(goalrollupqueryid);
    }

    @Override
    public void removeByRollupqueryinprogressmoneyid(String goalrollupqueryid) {
        this.remove(new QueryWrapper<Goal>().eq("rollupqueryinprogressmoneyid",goalrollupqueryid));
    }

	@Override
    public List<Goal> selectByGoalwitherrorid(String goalid) {
        return baseMapper.selectByGoalwitherrorid(goalid);
    }

    @Override
    public void removeByGoalwitherrorid(String goalid) {
        this.remove(new QueryWrapper<Goal>().eq("goalwitherrorid",goalid));
    }

	@Override
    public List<Goal> selectByParentgoalid(String goalid) {
        return baseMapper.selectByParentgoalid(goalid);
    }

    @Override
    public void removeByParentgoalid(String goalid) {
        this.remove(new QueryWrapper<Goal>().eq("parentgoalid",goalid));
    }

	@Override
    public List<Goal> selectByMetricid(String metricid) {
        return baseMapper.selectByMetricid(metricid);
    }

    @Override
    public void removeByMetricid(String metricid) {
        this.remove(new QueryWrapper<Goal>().eq("metricid",metricid));
    }


    /**
     * 查询集合 DEFAULT
     */
    @Override
    public Page<Goal> searchDefault(GoalSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Goal> pages=baseMapper.searchDefault(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Goal>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 停用
     */
    @Override
    public Page<Goal> searchStop(GoalSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Goal> pages=baseMapper.searchStop(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Goal>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }

    /**
     * 查询集合 可用
     */
    @Override
    public Page<Goal> searchUsable(GoalSearchContext context) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Goal> pages=baseMapper.searchUsable(context.getPages(),context,context.getSelectCond());
        return new PageImpl<Goal>(pages.getRecords(), context.getPageable(), pages.getTotal());
    }



    /**
     * 为当前实体填充父数据（外键值文本、外键值附加数据）
     * @param et
     */
    private void fillParentData(Goal et){
        //实体关系[DER1N_GOAL__GOAL__PARENTGOALID]
        if(!ObjectUtils.isEmpty(et.getParentgoalid())){
            cn.ibizlab.businesscentral.core.sales.domain.Goal parentgoal=et.getParentgoal();
            if(ObjectUtils.isEmpty(parentgoal)){
                cn.ibizlab.businesscentral.core.sales.domain.Goal majorEntity=goalService.get(et.getParentgoalid());
                et.setParentgoal(majorEntity);
                parentgoal=majorEntity;
            }
            et.setParentgoalname(parentgoal.getTitle());
        }
        //实体关系[DER1N_GOAL__METRIC__METRICID]
        if(!ObjectUtils.isEmpty(et.getMetricid())){
            cn.ibizlab.businesscentral.core.base.domain.Metric metric=et.getMetric();
            if(ObjectUtils.isEmpty(metric)){
                cn.ibizlab.businesscentral.core.base.domain.Metric majorEntity=metricService.get(et.getMetricid());
                et.setMetric(majorEntity);
                metric=majorEntity;
            }
            et.setMetricname(metric.getMetricname());
        }
    }




    @Override
    public List<JSONObject> select(String sql, Map param){
        return this.baseMapper.selectBySQL(sql,param);
    }

    @Override
    @Transactional
    public boolean execute(String sql , Map param){
        if (sql == null || sql.isEmpty()) {
            return false;
        }
        if (sql.toLowerCase().trim().startsWith("insert")) {
            return this.baseMapper.insertBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("update")) {
            return this.baseMapper.updateBySQL(sql,param);
        }
        if (sql.toLowerCase().trim().startsWith("delete")) {
            return this.baseMapper.deleteBySQL(sql,param);
        }
        log.warn("暂未支持的SQL语法");
        return true;
    }

    @Override
    public List<Goal> getGoalByIds(List<String> ids) {
         return this.listByIds(ids);
    }

    @Override
    public List<Goal> getGoalByEntities(List<Goal> entities) {
        List ids =new ArrayList();
        for(Goal entity : entities){
            Serializable id=entity.getGoalid();
            if(!ObjectUtils.isEmpty(id)){
                ids.add(id);
            }
        }
        if(ids.size()>0)
           return this.listByIds(ids);
        else
           return entities;
    }

}



